package com.github.ghsea.sso.client.security.permission.http;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

/**
 * Rest接口调用基类。主要用于查询用户权限和用户
 *
 * @param <R>
 */
public abstract class AbstractRestInvoker<R> {

    private Logger logger = LoggerFactory.getLogger(getClass());

    protected R invoke(String url) {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            String response = responseEntity.getBody();
            Gson gson = new Gson();
            logger.info("permission request.url:{},response:{}", url, response);
            RestResponse<R> ret = gson.fromJson(response, responseTypeToken().getType());
            return ret.getData();
        } else {
            throw new RequestFailedException("http request failed,responseCode=" + responseEntity.getStatusCode() + ",requestUrl=" + url);
        }
    }

    abstract TypeToken responseTypeToken();
}